Java8 Stream介绍 发表于 2020-10-27 | 分类于 Java | 阅读次数: 字数统计: 4,942 字 | 阅读时长 ≈ 30 分钟 直接上程序, 一些练习的例子全拿出来了 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076/** *filter使用,找到第一个,找不到返回null, */ @Test public void streamTest() { List<String> lists = Lists.newArrayList(null, null, "bb", "cc"); String str = lists.stream().filter(st -> "aa".equals(st)).findFirst().orElse(null); System.out.println(str); } @Test public void testOptional() { //没有删除方法 List<String> names = Arrays.asList("Mal", "Wash", "Kaylee", "Inara", "Zoë", "Jayne", "Simon", "River", "Shepherd Book", "CA"); Optional<String> first = names.stream().filter(name -> name.startsWith("C")).findFirst(); System.out.println(first); System.out.println(first.orElse("None")); System.out.println(first.orElse(getFormat(names))); System.out.println(first.orElseGet(() -> getFormat(names))); System.out.println(first.orElseThrow(() -> new NullPointerException("异常"))); } private String getFormat(List<String> names) { System.out.println(names); return String.format("No result found in %s", names.stream().collect(Collectors.joining(", "))); } @Test public void testPredicate() { List<String> names = Lists.newArrayList("Mal", "Wash", "Kaylee", "Inara", "Zoë", "Jayne", "Simon", "River", null, "Shepherd Book", "CA"); Predicate<String> predicate = s -> s != null; predicate = predicate.and(s -> s.length() == 5); System.out.println(getNamesOfLength(predicate, names)); System.out.println(names.removeIf(s -> s == null || s.length() == 5)); System.out.println(names); } private String getNamesOfLength(Predicate<String> predicate, List<String> names) { return names.stream().filter(predicate).collect(Collectors.joining(", ")); } @Test public void testFunction() { ArrayList<String> names = Lists.newArrayList("Mal", "Wash", "Kaylee", "Inara", "Zoë", "Jayne", "Simon", "River", "Shepherd Book"); //匿名内部类 List<Integer> nameLengths2 = names.stream().map(new Function<String, Integer>() { @Override public Integer apply(String s) { return s.length(); } }).collect(toList()); //lambda表达式 List<Integer> nameLengths = names.stream().map(s -> s.length()).collect(toList()); //方法引用 List<Integer> nameLengths1 = names.stream().map(String::length).collect(toList()); System.out.println(nameLengths); Map<String, Integer> map = new HashMap<>(); map.put("11", 1); map.computeIfPresent("11", (k, v) -> v = v + 1); System.out.println(map); } @Test public void testStream() { Stream.generate(Math::random).limit(10).forEach(System.out::println); List<Integer> ints = IntStream.range(10, 15).boxed().collect(toList()); System.out.println(ints); List<Integer> ints2 = IntStream.rangeClosed(10, 15).boxed().collect(toList()); List<Integer> ints3 = IntStream.rangeClosed(10, 15).mapToObj(Integer::valueOf).collect(toList()); System.out.println(ints2); } @Test public void testCollect() { List<Integer> ints = IntStream.of(3, 1, 4, 1, 5, 9) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); System.out.println(ints); int[] intArray = IntStream.of(3, 1, 4, 1, 5, 9).toArray(); System.out.println(Arrays.toString(intArray)); } /**统计的api**/ @Test public void testCount() { String[] strings = "this is an array of strings".split(" "); long count = Arrays.stream(strings).map(String::length).count(); System.out.println(count); int totalLength = Arrays.stream(strings).mapToInt(String::length).sum(); System.out.println(totalLength); OptionalDouble ave = Arrays.stream(strings).mapToInt(String::length).average(); System.out.println(ave.getAsDouble()); System.out.println(Double.NaN); OptionalInt max = Arrays.stream(strings).mapToInt(String::length).max(); System.out.println(max.getAsInt()); OptionalInt min = Arrays.stream(strings).mapToInt(String::length).min(); System.out.println(min.getAsInt()); int sum = Arrays.stream(strings).mapToInt(String::length).reduce((x, y) -> x + y).orElse(0); System.out.println(sum); } /**String字符串拼接*/ @Test public void testReduceStrJoin1() { String s = Stream.of("this", "is", "a", "list") .collect(() -> new StringBuilder(), (sb, str) -> sb.append(str), (sb1, sb2) -> sb1.append(sb2)) .toString(); System.out.println(s); } /**其他类型的可以通过StringUtils进行拼接:List<Long> teacherIds = Lists.newArrayList(12L,13L,18L);String teacherIdsStr = StringUtils.join(teacherIds.iterator(), ",");**/ @Test public void testReduceStrJoin2() { String s = Stream.of("this", "is", "a", "list") .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString(); System.out.println(s); } @Test public void testReduceStrJoin3() { String s = Stream.of("this", "is", "a", "list") .collect(Collectors.joining()); System.out.println(s); } @Test public void testReducePrim() { List<Book> books = Lists.newArrayList( new Book(1, "Java 1"), new Book(1, "Java 2"), new Book(3, "Java 3"), new Book(4, "Java 4") ); HashMap<Integer, Book> bookMap = books.stream() .reduce(new HashMap<>(), (map, book) -> { map.put(book.getId(), book); return map; }, (map1, map2) -> { map1.putAll(map2); return map1; }); bookMap.forEach((k, v) -> System.out.println(k + ": " + v)); }/***List 变 map*Collectors.toMap(Book::getId, b -> b) 第一个参数是key,第二个是value, 不允许有重复的*下面允许将重复的保留第几个*Collectors.toMap(Book::getId, Function.identity(), (k1, k2) -> k2)*/ @Test public void testReducetoMap() { List<Book> books = Lists.newArrayList( new Book(1, "Java 1"), new Book(1, "Java 2"), new Book(3, "Java 3"), new Book(4, "Java 4") ); //不允许重复的 //Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(Book::getId, b -> b)); //重复的归并到第二个 Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(Book::getId, Function.identity(), (k1, k2) -> k2)); bookMap.forEach((k, v) -> System.out.println(k + ": " + v)); } //reduce操作 @Test public void testReduceSum() { BigDecimal total = Stream.iterate(BigDecimal.ONE, n -> n.add(BigDecimal.ONE)) .limit(10) .reduce(BigDecimal.ZERO, (acc, val) -> acc.add(val)); System.out.println("The total is " + total); } @Test public void testReduceSort() { List<String> strings = Lists.newArrayList( "this", "is", "a", "list", "of", "strings"); List<String> sorted = strings.stream() .sorted(Comparator.comparingInt(String::length)) .collect(toList()); System.out.println(sorted); sorted.stream() .reduce((prev, curr) -> { assertTrue(prev.length() <= curr.length()); return curr; }); } @Test public void sumDoublesDivisibleBy3() { assertEquals(1554, sumDoublesDivisibleBy3(100, 120)); } public int sumDoublesDivisibleBy3(int start, int end) { return IntStream.rangeClosed(start, end) .peek(n -> System.out.printf("original: %d%n", n)) .map(n -> n * 2) .peek(n -> System.out.printf("doubled: %d%n", n)) .filter(n -> n % 3 == 0) .peek(n -> System.out.printf("filtered: %d%n", n)) .sum(); } @Test public void testPalindrome() { String str = "asisA"; System.out.println(isPalindrome1(str)); } public boolean isPalindrome(String s) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isLetterOrDigit(c)) { sb.append(c); } } String forward = sb.toString().toLowerCase(); String backward = sb.reverse().toString().toLowerCase(); return forward.equals(backward); } public boolean isPalindrome1(String s) { String forward = s.toLowerCase().codePoints() .filter(Character::isLetterOrDigit) .peek(n -> System.out.println(n)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); String backward = new StringBuilder(forward).reverse().toString(); return forward.equals(backward); } /** * count是一种特殊的归约,相当于 * long count = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5).mapToLong(e->1L).sum(); * return mapToLong(e -> 1L).sum(); */ @Test public void testItemsCount() { long count = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5).count(); System.out.printf("There are %d elements in the stream%n", count); } /** * Function.identity() 也就是 return t -> t; */ @Test public void testD() { List<Book> books = Lists.newArrayList( new Book(1, "Java 1"), new Book(1, "Java 2"), new Book(3, "Java 3"), new Book(4, "Java 4") ); Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(b -> b.getId(), Function.identity(), (k1, k2) -> k2)); System.out.println(bookMap); } @Test public void testPartitioning() { List<String> strings = Lists.newArrayList( "this", "is", "a", "list", "of", "strings"); Map<Boolean, Long> numberLengthMap = strings.stream() .collect(Collectors.partitioningBy( s -> s.length() % 2 == 0, Collectors.counting())); Map<Boolean, List<String>> stringsPartitionMap = strings.stream() .collect(Collectors.partitioningBy( s -> s.length() % 2 == 0)); numberLengthMap.forEach((k, v) -> System.out.printf("%5s: %d%n", k, v)); System.out.println(stringsPartitionMap); } /** * 用户希望获取数值流中元素的数量、总和、最小值、最大值以及平均值。 */ @Test public void testSummaryStatistics() { //DoubleStream.generate(Math::random) List<Double> doubleList = Lists.newArrayList(1.0, 2.1, 3.4); DoubleSummaryStatistics stats = doubleList.stream().mapToDouble(d -> d) .summaryStatistics(); System.out.println(stats); System.out.println("count: " + stats.getCount()); System.out.println("min : " + stats.getMin()); System.out.println("max : " + stats.getMax()); System.out.println("sum : " + stats.getSum()); System.out.println("ave : " + stats.getAverage()); } @Test public void testOptionalFindFirst() { Optional<Integer> firstEvenGT10 = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5) .peek(i -> System.out.println(i)) .filter(n -> n % 2 == 0) .findFirst(); System.out.println(firstEvenGT10); } @Test public void testHash() { List<String> wordList = Arrays.asList( "this", "is", "a", "stream", "of", "strings"); Set<String> words = new HashSet<>(wordList); Set<String> words2 = new HashSet<>(words); // 接下来,添加和删除足够多的元素来强制进行再散列操作 IntStream.rangeClosed(0, 50).forEachOrdered(i -> words2.add(String.valueOf(i))); words2.retainAll(wordList); // 这些集合是相等的,但具有不同的元素排序 System.out.println(words.equals(words2)); System.out.println("Before: " + words); System.out.println("After : " + words2); } @Test public void testFindAny() { Optional<Integer> any = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5) .unordered() .parallel() .map(this::delay) .findAny(); System.out.println("Any: " + any); } public Integer delay(Integer n) { try { Thread.sleep((long) (Math.random() * 100)); } catch (InterruptedException ignored) { } return n; } public boolean isPrime(int num) { int limit = (int) Math.sqrt(num) + 1; return num == 2 || num > 1 && IntStream.range(2, limit).noneMatch(divisor -> num % divisor == 0); } @Test public void testIsPrimeUsingAllMatch() throws Exception { assertTrue(IntStream.of(2, 3, 5, 7, 11, 13, 17, 19) .allMatch(i -> isPrime(i))); } @Test public void testIsPrimeWithComposites() throws Exception { assertFalse(Stream.of(4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20) .anyMatch(i -> isPrime(i))); } @Test public void emptyStreamsDanger() { assertTrue(Stream.empty().allMatch(e -> false)); assertTrue(Stream.empty().noneMatch(e -> true)); assertFalse(Stream.empty().anyMatch(e -> true)); } @Test public void testFlatMap() { Customer sheridan = new Customer("Sheridan"); Customer ivanova = new Customer("Ivanova"); Customer garibaldi = new Customer("Garibaldi"); sheridan.addOrder(new Order(1)) .addOrder(new Order(2)) .addOrder(new Order(3)); ivanova.addOrder(new Order(4)) .addOrder(new Order(5)); List<Customer> customers = Lists.newArrayList(sheridan, ivanova, garibaldi); customers.stream().map(Customer::getName).forEach(System.out::println); customers.stream() .map(Customer::getOrders) .forEach(System.out::println); customers.stream() .map(customer -> customer.getOrders().stream()) .forEach(System.out::println); customers.stream() .flatMap(customer -> customer.getOrders().stream()) .forEach(System.out::println); } @Test public void testStreamConcat() { Stream<String> first = Stream.of("a", "b", "c").parallel(); Stream<String> second = Stream.of("X", "Y", "Z"); Stream<String> third = Stream.of("alpha", "beta", "gamma"); Stream<String> fourth = Stream.empty(); List<String> strings = Stream.of(first, second, third, fourth) .reduce(Stream.empty(), Stream::concat) .collect(Collectors.toList()); System.out.println(strings); } @Test public void flatMap() { Stream<String> first = Stream.of("a", "b", "c").parallel(); Stream<String> second = Stream.of("X", "Y", "Z"); Stream<String> third = Stream.of("alpha", "beta", "gamma"); Stream<String> fourth = Stream.empty(); List<String> strings = Stream.of(first, second, third, fourth) .flatMap(Function.identity()) .collect(Collectors.toList()); List<String> stringList = Arrays.asList("a", "b", "c", "X", "Y", "Z", "alpha", "beta", "gamma"); assertEquals(stringList, strings); } @Test public void flatMapParallel() { Stream<String> first = Stream.of("a", "b", "c").parallel(); Stream<String> second = Stream.of("X", "Y", "Z"); Stream<String> third = Stream.of("alpha", "beta", "gamma"); Stream<String> fourth = Stream.empty(); Stream<String> total = Stream.of(first, second, third, fourth) .flatMap(Function.identity()); assertFalse(total.isParallel()); total = total.parallel(); assertTrue(total.isParallel()); } @Test public void testFilter() { List<Book> books = Lists.newArrayList( new Book(1, "Java 1"), new Book(1, null), new Book(3, null), new Book(4, "Java 4") ); List<Book> booksFilter = books.stream().filter(t -> t.getId() != 1 && t.getTitle() != null).collect(Collectors.toList()); System.out.println(booksFilter); } @Test public void testToSet() { List<String> actors = Stream.of("Hank Azaria", "Janeane Garofalo", "William H. Macy", "Paul Reubens", "Ben Stiller", "Kel Mitchell", "Wes Studi") .collect(Collectors.toCollection(LinkedList::new)); System.out.println(actors); } @Test public void testToArray() { String[] actors = Stream.of("Hank Azaria", "Janeane Garofalo", "William H. Macy", "Paul Reubens", "Ben Stiller", "Kel Mitchell", "Wes Studi").toArray(String[]::new); System.out.println(actors); } @Test public void testMap() { Set<Book> books = Sets.newHashSet( new Book(1, "A Java 1"), new Book(1, "C Java 2"), new Book(3, "D Java 3"), new Book(4, "B Java 4")); Map<Integer, String> bookMap = books.stream() .collect(Collectors.toMap(Book::getId, Book::getTitle, (k1, k2) -> k2)); bookMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())). forEach(entry -> System.out.printf("%s name %s%n", entry.getKey(), entry.getValue())); } /** * 分区, 满足predicate的, 不满足predicate的 */ @Test public void testPartition() { List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of", "strings", "to", "use", "as", "a", "demo"); Map<Boolean, List<String>> lengthMap = strings.stream() .collect(Collectors.partitioningBy(s -> s.length() % 2 == 0)); lengthMap.forEach((key, value) -> System.out.printf("%5s: %s%n", key, value)); } /** * 下游收集器 */ @Test public void testPartitionDownStream() { List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of", "strings", "to", "use", "as", "a", "demo"); Map<Boolean, Long> lengthNum = strings.stream() .collect(Collectors.partitioningBy(s -> s.length() % 2 == 0, Collectors.counting())); lengthNum.forEach((key, value) -> System.out.printf("%5s: %s%n", key, value)); } @Test public void testGrouping() { List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of", "strings", "to", "use", "as", "a", "demo"); Map<Integer, List<String>> lengthMap = strings.stream() .collect(Collectors.groupingBy(String::length)); lengthMap.forEach((k, v) -> System.out.printf("%d: %s%n", k, v)); } @Test public void testMinMax() { List<Employee> employees = Arrays.asList( new Employee("Cersei", 250_000, "Lannister"), new Employee("Jamie", 150_000, "Lannister"), new Employee("Tyrion", 1_000, "Lannister"), new Employee("Tywin", 1_000_000, "Lannister"), new Employee("Jon Snow", 75_000, "Stark"), new Employee("Robb", 120_000, "Stark"), new Employee("Eddard", 125_000, "Stark"), new Employee("Sansa", 0, "Stark"), new Employee("Arya", 1_000, "Stark")); Employee defaultEmployee = new Employee("A man (or woman) has no name", 0, "Black and White"); Optional<Employee> optionalEmp = employees.stream() .collect(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary))); System.out.println(optionalEmp); Map<String, Optional<Employee>> groupByPartment = employees.stream() .collect(Collectors.groupingBy( Employee::getDepartment, Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)))); System.out.println(groupByPartment); } @Test public void testUnmodifyable() { Map<String, Integer> map = Collections.unmodifiableMap( new HashMap<String, Integer>() {{ put("have", 1); put("the", 2); put("high", 3); put("ground", 4); }}); } } class Employee { private String name; private Integer salary; private String department; // 其他方法 public Employee(String name, Integer salary, String department) { this.name = name; this.salary = salary; this.department = department; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", salary=" + salary + ", department='" + department + '\'' + '}'; }} class Book { private Integer id; private String title; // 构造函数、getter和setter、toString、equals、hashCode… public Book() { } public Book(Integer id, String title) { this.id = id; this.title = title; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + '}'; }} class Customer { private String name; private List<Order> orders = new ArrayList<>(); public Customer(String name) { this.name = name; } public String getName() { return name; } public List<Order> getOrders() { return orders; } public Customer addOrder(Order order) { orders.add(order); return this; }} class Order { private int id; public Order(int id) { this.id = id; } public int getId() { return id; } @Override public String toString() { return "Order{" + "id=" + id + '}'; }} package com.east.service; import com.google.common.collect.Lists;import com.google.common.collect.Maps;import org.junit.Test; import java.io.IOException;import java.math.BigInteger;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.time.*;import java.util.*;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.logging.Logger;import java.util.stream.Collectors;import java.util.stream.Stream; import static junit.framework.TestCase.assertTrue; /** * @author zhaomingwei * Created on 18/9/20. */public class Lambda2Test { @Test public void testObjectNonNull() { List<String> strings = Arrays.asList( "this", null, "is", "a", null, "list", "of", "strings", null); List<String> nonNullStrings = strings.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); System.out.println(nonNullStrings); List<String> strings2 = Arrays.asList("this", "is", "a", "list", "of", "strings"); assertTrue(Objects.deepEquals(strings2, nonNullStrings)); assertTrue(strings2.equals(nonNullStrings)); } /** * 从泛型中去掉空元素 * * @param list * @param <T> * * @return */ public <T> List<T> getNonNullElements(List<T> list) { return list.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); } @Test public void testRequireNonNull() { String s = null; Objects.requireNonNull(s, () -> "不能为空"); } private Map<Long, BigInteger> cache = new HashMap<>(); @Test public void testMapNew() { long time1 = System.nanoTime(); fib(70); long time2 = System.nanoTime(); System.out.println(time2 - time1); //fib2(70); long time3 = System.nanoTime(); System.out.println(time3 - time2); System.out.println(cache); } //computeIfAbsent如果键存在,返回对应的值,否则通过提供的函数计算新的值并保存 public BigInteger fib(long i) { if (i == 0) { return BigInteger.ZERO; } else if (i == 1) { return BigInteger.ONE; } return cache.computeIfAbsent(i, n -> fib(n - 2).add(fib(n - 1))); } //巨慢 public long fib2(long i) { if (i == 0) { return 0; } else if (i == 1) { return 1; } return fib2(i - 2) + fib2(i - 1); } @Test public void testMapPresent() { String sentence = "hello world hello kitty"; String[] strings = sentence.split(" "); Map<String, Integer> wordCount = new HashMap<>(); Arrays.stream(strings).forEach(s -> wordCount.merge(s, 1, Integer::sum)); System.out.println(wordCount); } //冲突 public interface Company { default String getName() { return "Initech"; } // 其他方法 } public interface Employee { String getFirst(); String getLast(); void convertCaffeineToCodeForMoney(); default String getName() { return String.format("%s %s", getFirst(), getLast()); } } public class CompanyEmployee implements Company, Employee { private String first; private String last; @Override public void convertCaffeineToCodeForMoney() { System.out.println("Coding..."); } @Override public String getFirst() { return first; } @Override public String getLast() { return last; } @Override public String getName() { return String.format("%s %s", Employee.super.getName(), Company.super.getName()); } } //Function 接口定义的复合方法 @Test public void testFunctionCompose() { Function<Integer, Integer> add2 = x -> x + 2; Function<Integer, Integer> mult3 = x -> x * 3; Function<Integer, Integer> mult3add2 = add2.compose(mult3); Function<Integer, Integer> add2mult3 = add2.andThen(mult3); System.out.println("mult3add2(1): " + mult3add2.apply(1)); System.out.println("add2mult3(1): " + add2mult3.apply(1)); } //Consumer 接口定义的复合方法 @Test public void testConsumer() { Logger log = Logger.getLogger(""); Consumer<String> printer = System.out::println; Consumer<String> logger = log::info; Consumer<String> printThenLog = printer.andThen(logger); Stream.of("this", "is", "a", "stream", "of", "strings").forEach(printThenLog); } //Predicate 接口定义的复合方法 @Test public void testPredicate() { Predicate<String> p = s -> s != null; Predicate<String> p2 = p.and(s -> s.length() > 0); String s = ""; System.out.println(p2.test(s)); } @Test public void testOptional() { Optional optional = Optional.ofNullable(null); System.out.println(optional.orElseGet(() -> Integer.parseInt("10000"))); Optional<String> firstEven = Stream.of("five", "even", "length", "string", "values") .filter(s -> s.length() % 2 == 0) .findFirst(); System.out.println(firstEven.orElse("null")); } @Test public void testIO() { try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) { lines.filter(s -> s.length() > 20) .sorted(Comparator.comparingInt(String::length).reversed()) .limit(10) .forEach(w -> System.out.printf("%s (%d)%n", w, w.length())); } catch (IOException e) { e.printStackTrace(); } } @Test public void testLettersNumIO() { try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) { lines.filter(s -> s.length() > 20) .collect(Collectors.groupingBy(String::length, Collectors.counting())) .forEach((len, num) -> System.out.println(len + ": " + num)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testLettersNumOrder() { try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) { Map<Integer, Long> map = lines.filter(s -> s.length() > 20) .collect(Collectors.groupingBy(String::length, Collectors.counting())); map.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); } catch (IOException e) { e.printStackTrace(); } } /** * 文件系统的遍历 */ @Test public void testFileScan() { try (Stream<Path> paths = Files.walk(Paths.get("src/main/java"))) { paths.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } @Test public void testFileFind() { try (Stream<Path> paths = Files.find(Paths.get("src/main/java"), Integer.MAX_VALUE, (path, attributes) -> !attributes.isDirectory() && path.toString().contains("Lambda"))) { paths.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } @Test public void testTimeNow() { System.out.println("Instant.now(): " + Instant.now()); System.out.println("LocalDate.now(): " + LocalDate.now()); System.out.println("LocalTime.now(): " + LocalTime.now()); System.out.println("LocalDateTime.now(): " + LocalDateTime.now()); System.out.println("ZonedDateTime.now(): " + ZonedDateTime.now()); } @Test public void testTimeOf() { System.out.println("First landing on the Moon:"); LocalDate moonLandingDate = LocalDate.of(1969, Month.JULY, 20); LocalTime moonLandingTime = LocalTime.of(20, 18); System.out.println("Date: " + moonLandingDate); System.out.println("Time: " + moonLandingTime); System.out.println("Neil Armstrong steps onto the surface: "); LocalTime walkTime = LocalTime.of(20, 2, 56, 150_000_000); LocalDateTime walk = LocalDateTime.of(moonLandingDate, walkTime); System.out.println(walk); } @Test public void convertDateToLocalDate() { LocalDate localDate = convertFromUtilDateUsingInstant(new Date()); System.out.println(localDate); } public LocalDate convertFromUtilDateUsingInstant(Date date) { return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public LocalDateTime convertFromCalendarUsingGetters(Calendar cal) { return LocalDateTime.of(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); } @Test public void testTiming() { Instant start = Instant.now(); // 调用需要计时的方法 List<Integer> list = Lists.newArrayList(); for (int i = 0; i < 1024000; i++) { list.add(Integer.valueOf(i)); if (i % 10 == 0) { System.gc(); } } Instant end = Instant.now(); System.out.println(getTiming(start, end) + " seconds"); } public static double getTiming(Instant start, Instant end) { return Duration.between(start, end).toMillis() / 1000.0; } @Test public void testList() { Lists.newArrayList(); } @Test public void testTreeMap() { //List<Integer> numbers = IntStream.range(-10, 10).boxed().collect(toList()); List<Integer> numbers = Lists.newArrayList(-10, -9, -8, -7, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -5, 8, -6, 9); System.out.println(numbers); Map<Integer, Integer> map = Maps.newTreeMap(Comparator.<Integer>reverseOrder()); for (Integer i : numbers) { map.put(i, i); } map.forEach((k, v)-> System.out.printf("%d, %d\n",k,v)); System.out.println(); } @Test public void testTreeMap2() { //List<Integer> numbers = IntStream.of(3, 1, 4, 1, -1, -3, 9).boxed().collect(toList()); //List<Integer> numbers = new Random().ints().limit(10).boxed().collect(toList()); List<Integer> numbers = Lists.newArrayList(1033293453, 1688703861, -1397662954, 1358394462, 2144737669, 1683364491, 906680402, 2094148244, 898301002, 134828019); System.out.println(numbers); //TreeMap<Integer, Integer> map = Maps.newTreeMap(Comparator.<Integer>reverseOrder()); // 正确写法 //TreeMap<Integer, Integer> map = Maps.newTreeMap((o1, o2) -> o2 - o1);//错误, TreeMap<Integer, Integer> map = Maps.newTreeMap((o1, o2) -> o2.compareTo(o1)); for (Integer i : numbers) { map.put(i, i); } map.forEach((k, v)-> System.out.printf("%d, %d\n",k,v)); System.out.println(); }@Testpublic void testParallelStream() { List<Long> list = LongStream.range(0, 10000).boxed().collect(Collectors.toList()); Stopwatch stopwatch = Stopwatch.createStarted(); logger.info("start"); Lists.partition(list, 2000).parallelStream().forEach(l -> { try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } }); long end1 = stopwatch.elapsed(TimeUnit.MILLISECONDS); logger.info("end:{}", end1); Lists.partition(list, 2000).stream().forEach(l -> { try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } }); long end2 = stopwatch.elapsed(TimeUnit.MILLISECONDS); logger.info("end:{}", end2 - end1);}} -------------感谢您的阅读祝您生活愉快!------------- 支持一杯咖啡 打赏 微信支付